package cn.tedu.search.config;

import cn.tedu.search.domain.Cron;
import cn.tedu.search.mapper.CronMapper;
import cn.tedu.search.service.IndexService;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import java.time.LocalDateTime;
import java.util.List;

@Configuration
@EnableScheduling
public class DynamicScheduleTask implements SchedulingConfigurer {
    @Autowired
    private CronMapper cronMapper;
    @Autowired
    private IndexService indexService;
    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        taskRegistrar.addTriggerTask(
                //1.添加任务内容(Runnable)
                () -> {System.err.println("执行动态定时任务时间: " + LocalDateTime.now());
                    try {
                        indexService.createIndex("index10");
                        //测试使用
                        //indexService.query("我的",1,20,8);
                    } catch (JsonProcessingException e) {
                        e.printStackTrace();
                    }},
                //2.设置执行周期(Trigger)
                triggerContext -> {
                    //2.1 从数据库获取执行周期
                    List<Cron> crons = cronMapper.selectCron();
                    String cron = crons.get(0).getCron();
                    //2.2 合法性校验.
                    if (StringUtils.isEmpty(cron)) {
                        System.out.println("cron字段不能为空");
                    }
                    //2.3 返回执行周期(Date)
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
                }
        );
    }
}
